/**
 * This file is part of AudioStream.
 * Copyright (C) 2010 Justin Li and Jacob Wirth
 *
 *  AudioStream is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AudioStream is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AudioStream.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */

package org.frustra.audiostream.util;

public class Base64 {
	/**
	 * Character set for base64 encoding
	 */
	private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	
	/**
	 * Pads an array of bytes with zeros
	 * 
	 * @param length The target length of the array
	 * @param bytes The array to be padded
	 * @return The padded array
	 */
	private static byte[] zeroPad(int length, byte[] bytes) {
		byte[] padded = new byte[length];
		System.arraycopy(bytes, 0, padded, 0, bytes.length);
		return padded;
	}
	
	/**
	 * Base64 encodes a string
	 * 
	 * @param string The string to be encoded
	 * @return The encoded string
	 */
	public static String encode(String string) {
		String encoded = "";
		byte[] stringArray;
		try {
			stringArray = string.getBytes("UTF-8");  
		} catch (Exception e) {
			stringArray = string.getBytes();
		}
		
		int paddingCount = (3 - (stringArray.length % 3)) % 3;
		
		stringArray = zeroPad(stringArray.length + paddingCount, stringArray);
		for (int i = 0; i < stringArray.length; i += 3) {
			int j = ((stringArray[i] & 0xff) << 16) + ((stringArray[i + 1] & 0xff) << 8) + (stringArray[i + 2] & 0xff);
			encoded = encoded + base64code.charAt((j >> 18) & 0x3f) + base64code.charAt((j >> 12) & 0x3f) + base64code.charAt((j >> 6) & 0x3f) + base64code.charAt(j & 0x3f);
		}
		return encoded.substring(0, encoded.length() - paddingCount) + ("==").substring(0, paddingCount);
	}
}